package com.controller;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;


import com.model.Agent;
import com.service.AgentService;
import com.service.BranchService;

@Controller
public class AgentController {
	
	@Autowired
	private AgentService agentService;
	
	@Autowired
	private BranchService branchService;
	
	
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public ModelAndView index() {
		return new ModelAndView("index");
	}
	
	
	// REquest to add agent.. Give blank form of agent
	@RequestMapping(value="/user/addAgent",method=RequestMethod.GET)
	public ModelAndView addAgent(HttpSession session,@ModelAttribute("command") Agent agent) {
		Map<String, Object> model = new HashMap<String, Object>();
		return new ModelAndView("agent",model);
	}
	
	// add agent details into database
	@RequestMapping(value = "/user/saveAgent", method = RequestMethod.POST)
	public String saveAgent(HttpSession session,@ModelAttribute("command") Agent agent,ModelMap model) {
			agentService.add(session.getAttribute("branch").toString(),agent);
			return "redirect:/user/addAgent.htm";
	}
	
	// give agent details from database
	@RequestMapping("/user/editAgent")
    public ModelAndView editAgent(@ModelAttribute("command") Agent agent,
    		HttpServletRequest request)
    {
		Integer id=Integer.parseInt(request.getParameter("id"));
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("agent",agentService.get(id));
        return new ModelAndView("agent",model);
    }
	
	//delete Agent
	@RequestMapping("/user/deleteAgent")
    public String deleteAgent(HttpServletRequest request)
    {
		Integer id=Integer.parseInt(request.getParameter("id"));
        agentService.delete(id);
        return "redirect:/user/addAgent.htm";
    }

				
}
